﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using System.Globalization;
using System.Diagnostics;
using RelationTextBox;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Threading;
using System.Reflection;


namespace ESRP
{
    public partial class OptiuniRapoarteFrm : FrmCard
    {

        private FormSaveInfo _fInfoSave = new FormSaveInfo();
        enum TipLista { Balanta = 1,FisaCont=2,RegistruJurnal=4,RegistruCasa=5,ExtrasCont=6,ExecutieCheltuieli=11,ExecutiecheltuieliCentralizata=13 };
        private CultureInfo cultureRO = new CultureInfo("ro-RO");
        private TipLista tipRaport = TipLista.Balanta;
        private Boolean bDocumentJustifRulaj = false;
        ESRPDataSetListe.BalconSetupRow bRowSetup = null;
        private Int16 m_IdLista = 0;


        public OptiuniRapoarteFrm(Int16 tRap,ModuleClass mc):base(mc)
        {
            tipRaport = (TipLista)tRap;
            InitializeComponent();
            DeLaDataDTP.Format = DateTimePickerFormat.Custom;
            DeLaDataDTP.CustomFormat = "dd.MM.yyyy";
            PanaLaDataDTP.Format = DateTimePickerFormat.Custom;
            PanaLaDataDTP.CustomFormat = "dd.MM.yyyy";
            workConnString = mc.workConnectionString;
        }

        private void Setup(SqlConnection wConn)
        {
            Object ret = GetSetupValue("BalconSetup", "DocumentJustifRulaj", ModuleInfo.CodUnitate, wConn);
            Boolean val = false;
            if (ret == null || ret == DBNull.Value)
            {
                while (ret == null)
                {
                    SqlCommand comcfg = new SqlCommand("INSERT INTO BalconSetup (CodUnitate,AnCurent,LunaCurenta) VALUES (" + ModuleInfo.CodUnitate.ToString() + "," + DateTime.Now.Year.ToString() + "," + DateTime.Now.AddMonths(-1).Month.ToString() + ")",
                        wConn);
                    comcfg.ExecuteNonQuery();
                    ret = GetSetupValue("BalconSetup", "DocumentJustifRulaj", ModuleInfo.CodUnitate, wConn);
                }

            }
            val = (Boolean)ret;
            bDocumentJustifRulaj = val;

            if(balconSetupBindingSource.Count==0)
                return;
            bRowSetup = ((DataRowView)balconSetupBindingSource.Current).Row as  ESRPDataSetListe.BalconSetupRow;

            DateTime inceputLuna = new DateTime(bRowSetup.AnCurent, bRowSetup.LunaCurenta, 1);
            if(ModuleInfo.AnArhiva!=String.Empty)
                inceputLuna = new DateTime(Convert.ToInt16(ModuleInfo.AnArhiva), 1, 1);
            DateTime sfarsitLuna = inceputLuna.AddMonths(1).AddDays(-1);
            DeLaDataDTP.Value = inceputLuna;
            if (tipRaport == TipLista.ExecutieCheltuieli || tipRaport == TipLista.ExecutiecheltuieliCentralizata)
            {
                DeLaDataDTP.Value = new DateTime(DeLaDataDTP.Value.Year,1, DeLaDataDTP.Value.Day);
            }
            PanaLaDataDTP.Value = sfarsitLuna;
            if (tipRaport == TipLista.Balanta)
                DeLaDataDTP.Value = sfarsitLuna;
            jurnaleGB.Enabled = jurnaleBindingSource.Count != 0;

            TipListaCB.Visible = (tipRaport == TipLista.RegistruJurnal) || (tipRaport == TipLista.Balanta);
            TipListaL.Visible = tipRaport == TipLista.RegistruJurnal || (tipRaport == TipLista.Balanta);
            TipListaBindingSource.Add(new CategorieSursa("Financiar(a)", 0));
            TipListaBindingSource.Add(new CategorieSursa("De Gestiune", 1));
            TipListaBindingSource.Add(new CategorieSursa("În afara bilanţului", 2));
            TipListaBindingSource.Position = 0;

            PanaLaDataDTP.Visible = !(tipRaport == TipLista.Balanta);

            TipBalantaL.Visible = (tipRaport == TipLista.Balanta) || (tipRaport == TipLista.FisaCont);
            TipBalantaCB.Visible = (tipRaport == TipLista.Balanta) || (tipRaport == TipLista.FisaCont);
            switch(tipRaport)
            {
                case TipLista.Balanta:
                StilBalantaBindingSource.Add(new CategorieSursa("Generala", 0));
                StilBalantaBindingSource.Add(new CategorieSursa("ITCSF", 1));
                StilBalantaBindingSource.Add(new CategorieSursa("ITSCF", 2));
                break;
                case TipLista.FisaCont:
                StilBalantaBindingSource.Add(new CategorieSursa("Financiara", 0));
                StilBalantaBindingSource.Add(new CategorieSursa("Extra bilantiera", 1));
                TipBalantaL.Text = "Tip fisa:";
                break;

            }

            PerioadaL.Text = (tipRaport == TipLista.Balanta ? "La data:" : "In perioada:");

            DeLaContulL.Text = (tipRaport == TipLista.RegistruJurnal ? "Cont debit:" : "De la contul:");
            PanaLaContulL.Text = (tipRaport == TipLista.RegistruJurnal ? "Cont credit:" : "Până la contul:");

            ContCorespondentCB.Visible = tipRaport == TipLista.RegistruCasa || tipRaport == TipLista.ExtrasCont;

            ContDebitCB.Visible = (tipRaport == TipLista.RegistruJurnal) || (tipRaport == TipLista.ExtrasCont) || tipRaport == TipLista.Balanta
                || tipRaport == TipLista.ExecutiecheltuieliCentralizata || tipRaport == TipLista.ExecutieCheltuieli || tipRaport == TipLista.FisaCont;
            DeLaContulL.Visible = (tipRaport == TipLista.RegistruJurnal) || (tipRaport == TipLista.ExtrasCont) || tipRaport == TipLista.Balanta
                || tipRaport == TipLista.ExecutiecheltuieliCentralizata || tipRaport == TipLista.ExecutieCheltuieli || tipRaport == TipLista.FisaCont;
            DenumireContCB.Visible = (tipRaport == TipLista.RegistruJurnal) || (tipRaport == TipLista.ExtrasCont) || tipRaport == TipLista.Balanta
                || tipRaport == TipLista.ExecutiecheltuieliCentralizata || tipRaport == TipLista.ExecutieCheltuieli || tipRaport == TipLista.FisaCont;
           
            DataInTitluCB.Visible = tipRaport == TipLista.RegistruCasa;

            ContCreditCB.Visible = (tipRaport == TipLista.RegistruJurnal) || (tipRaport == TipLista.ExtrasCont) || tipRaport == TipLista.Balanta
                || tipRaport == TipLista.ExecutiecheltuieliCentralizata || tipRaport == TipLista.ExecutieCheltuieli || tipRaport == TipLista.FisaCont;
            DenumireContCreditCB.Visible = (tipRaport == TipLista.RegistruJurnal) || (tipRaport == TipLista.ExtrasCont) || tipRaport == TipLista.Balanta
                || tipRaport == TipLista.ExecutiecheltuieliCentralizata || tipRaport == TipLista.ExecutieCheltuieli || tipRaport == TipLista.FisaCont;
            PanaLaContulL.Visible = (tipRaport == TipLista.RegistruJurnal) || (tipRaport == TipLista.ExtrasCont) || tipRaport == TipLista.Balanta
                || tipRaport == TipLista.ExecutiecheltuieliCentralizata || tipRaport == TipLista.ExecutieCheltuieli || tipRaport == TipLista.FisaCont;

            ZiPerPaginaCB.Text = (tipRaport == TipLista.RegistruCasa ? "Fiecare zi pe o pagină:" : "Centralizat:");
            ZiPerPaginaCB.Visible = tipRaport == TipLista.RegistruCasa || tipRaport==TipLista.RegistruJurnal;
            AnaliticaCB.Visible = tipRaport == TipLista.Balanta || tipRaport == TipLista.FisaCont;

            DataDocJustSortCB.Visible = tipRaport == TipLista.RegistruCasa || tipRaport==TipLista.RegistruJurnal;

            compactCB.Visible = tipRaport == TipLista.RegistruCasa || tipRaport == TipLista.RegistruJurnal || tipRaport == TipLista.Balanta || tipRaport == TipLista.FisaCont;
            IgnoraNoteCB.Visible = (tipRaport == TipLista.ExtrasCont) || tipRaport == TipLista.ExecutiecheltuieliCentralizata || tipRaport == TipLista.ExecutieCheltuieli;
            IgnoraNoteL.Visible = (tipRaport == TipLista.ExtrasCont) || tipRaport == TipLista.ExecutiecheltuieliCentralizata || tipRaport == TipLista.ExecutieCheltuieli;
            ConturiFaraMiscariCB.Visible = tipRaport == TipLista.Balanta || tipRaport == TipLista.ExecutiecheltuieliCentralizata || tipRaport == TipLista.ExecutieCheltuieli || tipRaport == TipLista.FisaCont;
            TotalGrupeSiClaseCB.Visible = tipRaport == TipLista.Balanta;
            
            CentralizatCB.Visible = tipRaport == TipLista.ExecutiecheltuieliCentralizata || tipRaport == TipLista.ExecutieCheltuieli;
            ContExtinsCB.Visible = (tipRaport == TipLista.Balanta) && (bRowSetup.TipUnitate.Trim().ToUpper()=="B") ;

            FiltruAnaliticL.Visible = (tipRaport == TipLista.Balanta) || tipRaport == TipLista.FisaCont;
            FiltruAnaliticTB.Visible = (tipRaport == TipLista.Balanta) || tipRaport == TipLista.FisaCont;

            ESRPDataSetListe.ConturiRow select = ((DataRowView)conturiDebitBindingSource.AddNew()).Row as ESRPDataSetListe.ConturiRow;
            select.CodUnitate = ModuleInfo.CodUnitate;
            select.Cont = "---";
            select.Denumire = "Va rugăm să selectaţi un cont!";
            select.ContParinte = "N/A";
            select.Tip = "B";
            select.Terminal = true;
            select.EsteAnalitic = false;
            select.DebitInitial = Decimal.Zero;
            select.CreditInitial = Decimal.Zero;
            select.DebitPrecedent = Decimal.Zero;
            select.CreditPrecedent = Decimal.Zero;
            select.RulajCredit = Decimal.Zero;
            select.RulajDebit = Decimal.Zero;
            select.Sold = Decimal.Zero;
            select.Categorie = 0;

            conturiDebitBindingSource.EndEdit();
            conturiCreditBindingSource.Position = 0;
            conturiDebitBindingSource.Position = 0;

            LoadFormInfo();
        }

        private void OptiuniRapoarteFrm_Load(object sender, EventArgs e)
        {
            SqlConnection con = DeschideConexiune(workConnString);
            try
            {
                this.surseFinantareTableAdapter.Connection = con;
                this.surseFinantareTableAdapter.Fill(this.eSRPDataSetListe.SurseFinantare);

                this.semnaturiTableAdapter.Connection = con;
                this.semnaturiTableAdapter.Fill(this.eSRPDataSetListe.Semnaturi);

                this.numarNotaRulajeDocViewTableAdapter.Connection = con;
                this.numarNotaRulajeDocViewTableAdapter.Fill(this.eSRPDataSetListe.NumarNotaRulajeDocView, ModuleInfo.CodUnitate);
                if (tipRaport == TipLista.RegistruJurnal || tipRaport == TipLista.ExtrasCont || tipRaport == TipLista.Balanta
                    || tipRaport == TipLista.ExecutieCheltuieli || tipRaport == TipLista.ExecutiecheltuieliCentralizata || (tipRaport == TipLista.FisaCont))
                {
                    this.conturiTableAdapter.Connection = con;
                    this.conturiTableAdapter.Fill(this.eSRPDataSetListe.Conturi, ModuleInfo.CodUnitate);
                }
                this.jurnaleTableAdapter.Connection = con;
                this.jurnaleTableAdapter.Fill(this.eSRPDataSetListe.Jurnale, ModuleInfo.CodUnitate);
                this.valutaTableAdapter.Connection = con;
                this.valutaTableAdapter.Fill(this.eSRPDataSetListe.Valuta);
                this.balconSetupTableAdapter.Connection = con;
                this.balconSetupTableAdapter.Fill(this.eSRPDataSetListe.BalconSetup, ModuleInfo.CodUnitate);
                Setup(con);
            }
            catch (Exception ex)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare", ex.Message, String.Empty,MessageBoxFrm.ImaginiMB.StopIcon, null);
                mbt.AddButton("Iesire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
            }
            InchideConexiune(con);
            AddButton("Genereaza", global::ERPStudio.Properties.Resources.salvare1, GenereazaLista, ToolStripItemAlignment.Right, true);
            foreach (ESRPDataSetListe.NumarNotaRulajeDocViewRow drr in eSRPDataSetListe.NumarNotaRulajeDocView.Select("", "NumarNota"))
            {
                if (drr.NumarNota.Trim() != String.Empty)
                    this.IgnoraNoteCB.Items.Add(drr.NumarNota, false);
            }
            
        }

        private void GenereazaLista(object sender, EventArgs args)
        {
            Cursor.Current = Cursors.AppStarting;
            String linia1 = String.Empty, linia2 = String.Empty;

            PreviewRaportFrm frm = new PreviewRaportFrm("", null, ModuleInfo);
            
            String filtruTotal = String.Empty;
            switch (tipRaport)
            {

                case TipLista.Balanta: //Balanta
                    Balanta(frm, eSRPDataSetListe);
                    break;
                case TipLista.FisaCont: //Fisa Cont
                    FisaCont(frm, eSRPDataSetListe);
                    break;
                //case 3: //Cartea Mare
                //    CarteaMare(frm, eSRPDS);
                //    break;
                case TipLista.RegistruJurnal: //Registru Jurnal
                    if (!RegistruJurnal(frm, eSRPDataSetListe))
                        return;
                    break;
                case TipLista.RegistruCasa: //Registru Casa
                    if (!RegistruCasa(frm, eSRPDataSetListe, "Registru de casa"))
                        return;
                    break;
                case TipLista.ExtrasCont: //Extras de cont
                    ExtrasDeCont(frm, eSRPDataSetListe, "Extras de cont");
                    break;
                //case 7: //Extras de cont
                //    ExtrasDeCont(frm, eSRPDS, "Fise generale");
                //    break;
                //case 9: //Extras de cont
                //    MessageBox.Show("Lista nu este disponibila in aceasta versiune!");
                //    return;
                //case 10: //Operatiuni diverse
                //    if (!OperatiuniDiverse(frm, eSRPDS))
                //        return;
                //    break;
                case TipLista.ExecutieCheltuieli: //Extras de cont
                    ExecutieCheltuieli(frm, eSRPDataSetListe);
                    break;
                //case 12: //Extras de cont
                //    if (!ListaOperatiuni(frm, eSRPDS))
                //        return;
                //    break;
                case TipLista.ExecutiecheltuieliCentralizata: //Contul de executie al institutiilor publice
                    ExecutieCheltuieli(frm, eSRPDataSetListe);
                    break;
                //case 8: //Bilant
                //case 14: //Rezultat patrimonial
                //case 15: //Venituri si cheltuieli
                //    if (!Bilant(frm, eSRPDS))
                //        return;
                //    break;

            }

            frm.MdiParent = this.MdiParent;
            frm.Show();


            Cursor.Current = Cursors.Default;
        }

        private String FiltruCont = String.Empty;
        private String FiltruJurnal = String.Empty;
        private Boolean RegistruCasa(PreviewRaportFrm frm, ESRPDataSetListe eSRPDS, String Titlu)
        {
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
            String filtruData = String.Empty;

            DateTime dte = DateTime.MinValue, dt = DateTime.MaxValue;

            dte = DeLaDataDTP.Value;
            filtruData = " DataDoc >= @DataStart ";

            dt = PanaLaDataDTP.Value;
            if (filtruData != String.Empty)
                filtruData += "AND ";
            filtruData += " DataDoc <= @DataEnd ";

            
            String linia1 = Titlu + " ", linia2 = String.Empty; //+ tipJurn;
            if (!DataInTitluCB.Checked)
                linia2 += " in intervalul " + dte.ToString("d", cultureRO) + " - " + dt.ToString("d", cultureRO);

            cmd.CommandText = "SELECT [Cont] FROM [ConturiSpeciale] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND [Tipuri] like '%CCS%'";
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr == null || !dr.HasRows)
            {
                
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare", "Nu a fost definit niciun cont de casă!\nIn macheta următoare aveţi posibilitatea de a definii conturile de casă!", "Definiţi",MessageBoxFrm.ImaginiMB.IntrebareIcon, null);
                mbt.AddButton("Da", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();

                SetSpecialContFrm frmSet = new SetSpecialContFrm(ModuleInfo);
                frm.Text = "Setare conturi de casa:";
                frmSet.ShowDialog();
                dr.Close();
                dr = cmd.ExecuteReader();
                return false;
            }

            String filtruCont = String.Empty;
            FiltruCont = String.Empty;
            while (dr.Read())
            {
                if (filtruCont != String.Empty)
                    filtruCont += ",";
                filtruCont += "'" + dr["Cont"].ToString() + "'";

                if (FiltruCont != String.Empty)
                    FiltruCont += ",";
                FiltruCont += dr["Cont"].ToString();
            }
            dr.Close();


            String filtruContCredit = String.Empty;
            filtruContCredit = " AND CONTCREDIT IN  (" + filtruCont + ")";
            String filtruSume = " AND CONT IN  (" + filtruCont + ")";
            filtruCont = " AND CONTDEBIT IN  (" + filtruCont + ")";


            String sJurnal = GetJurnaleSelectate();
          ///sectiunea de jurnale
          ///
            FiltruJurnal = sJurnal; 
            

            SumDocFormula sdf = new SumDocFormula(cmd.Connection);
            sdf.CalcTotal(filtruSume, dte, dt,sJurnal, ModuleInfo);

            if (sJurnal != String.Empty)
            {
                linia2 += " pentru " + GetDenumireJurnaleSelectate();
            }

            this.balcon_GenRegistruCasa2TableAdapter.Connection = cmd.Connection;
            if(ModuleInfo.AnArhiva==String.Empty)
            this.balcon_GenRegistruCasa2TableAdapter.Fill(this.eSRPDataSetListe.balcon_GenRegistruCasa2,
                ModuleInfo.CodUnitate, DeLaDataDTP.Value, PanaLaDataDTP.Value, "%{CCS}%", String.Empty, String.Empty, DataDocJustSortCB.Checked);
            else
                this.balcon_GenRegistruCasa2TableAdapter.FillByArhiva(this.eSRPDataSetListe.balcon_GenRegistruCasa2,
                    ModuleInfo.CodUnitate, DeLaDataDTP.Value, PanaLaDataDTP.Value, "%{CCS}%", DataDocJustSortCB.Checked,ModuleInfo.AnArhiva);


            frm.NumeRaport = "RegistruCasa.rdlc";
            if(compactCB.Checked)
                frm.NumeRaport = "RegistruCasaCompact.rdlc";


            frm.dataloadHandler += new LoadDataHandler(frm_dataloadHandlerRegistruCasa);

            frm.AddDataSource("ESRPDataSet_BalconSetup", balconSetupBindingSource);
            frm.AddDataSource("balcon_GenRegistruCasa", balcon_GenRegistruCasa2BindingSource);

            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);

            frm.AddParameter("DebitInitial", sdf.debInit, true);
            frm.AddParameter("CreditInitial", sdf.creInit, true);
            frm.AddParameter("DebitPrecedent", sdf.debPrec, true);
            frm.AddParameter("CreditPrecedent", sdf.crePrec, true);
            frm.AddParameter("RulajDebit", sdf.debCurent, true);
            frm.AddParameter("RulajCredit", sdf.creCurent, true);
            frm.AddParameter("TotalSumeDebit", sdf.totalDeb, true);
            frm.AddParameter("TotalSumeCredit", sdf.totalCre, true);

            frm.AddParameter("ContCoresp", ContCorespondentCB.Checked ? "True" : "False", true);
            frm.AddParameter("DocumentJustificativ", (bDocumentJustifRulaj ? "True" : "False"), true);

            frm.AddParameter("PaginaPerZi", (ZiPerPaginaCB.Checked ? "True" : "False"), true);
            frm.AddParameter("Antet1Stanga", bRowSetup.IsLinia1StangaNull()?"":bRowSetup.Linia1Stanga, true);
            frm.AddParameter("Antet2Stanga", bRowSetup.IsLinia2StangaNull()?"":bRowSetup.Linia2Stanga, true);
            frm.AddParameter("Antet3Stanga", bRowSetup.IsLinia3StangaNull()?"":bRowSetup.Linia3Stanga, true);
            frm.AddParameter("Antet1Dreapta", bRowSetup.IsLinia1DreaptaNull()?"":bRowSetup.Linia1Dreapta, true);
            frm.AddParameter("Antet2Dreapta", bRowSetup.IsLinia2DreaptaNull()?"":bRowSetup.Linia2Dreapta, true);
            frm.AddParameter("Antet3Dreapta", bRowSetup.IsLinia3DreaptaNull()?"":bRowSetup.Linia3Dreapta, true);
            frm.AddParameter("DataInTitlu", (DataInTitluCB.Checked ? "True" : "False"), true);
            frm.AddParameter("GroupDataDocJust", (DataDocJustSortCB.Checked ? "True" : "False"), true);
            frm.SetWindowFormat(true);
            InchideConexiune(cmd.Connection);
            return true;
        }

        public void frm_dataloadHandlerRegistruCasa(object sender, Microsoft.Reporting.WinForms.SubreportProcessingEventArgs args)
        {
            ESRPDataSet eSRPDS = new ESRPDataSet();
            BindingSource bs = null;
            SqlDataAdapter ta = null;
            SqlConnection sqlConn = DeschideConexiune(workConnString);


            if (args.ReportPath == "RegistruCasaSubreport" || args.ReportPath == "RegistruCasaCompactSubreport")
            {
                Trace.Assert(args.Parameters.Count == 6, "Numar incorect de parametrii la subraport");
                CultureInfo culture;
                DateTimeStyles styles;
                DateTime dateResult;

                culture = Application.CurrentCulture;
                styles = DateTimeStyles.None;

                if (!DateTime.TryParse(args.Parameters["Data"].Values[0], culture, styles, out dateResult))
                    return;
                Boolean SortDataDocJust = Convert.ToBoolean(args.Parameters["GroupDataDocJust"].Values[0]);

                this.balcon_GenNotaContabilaUnionTableAdapter.Connection = sqlConn;
                this.balcon_GenNotaContabilaUnionTableAdapter.Fill(this.eSRPDataSetListe.balcon_GenNotaContabilaUnion, 
                   String.Empty, 
                    ModuleInfo.CodUnitate, 
                    dateResult, 
                    dateResult,
                    (ModuleInfo.AnArhiva == String.Empty) ? (Int16)0 : Convert.ToInt16(ModuleInfo.AnArhiva),
                    FiltruCont,
                    String.Empty,
                    FiltruJurnal);


                //bs = new BindingSource(eSRPDS, "NotaContabilaView");
                //ta = new SqlDataAdapter("GenNotaContabilaUnion", sqlConn);

                //ta.SelectCommand.CommandType = CommandType.StoredProcedure;
                //ta.SelectCommand.Parameters.Add(new SqlParameter("@cont", String.Empty));
                //ta.SelectCommand.Parameters.Add(new SqlParameter("@CodUnitate", ModuleInfo.CodUnitate));
                //ta.SelectCommand.Parameters.Add(new SqlParameter("@DeLaData", dateResult));
                //ta.SelectCommand.Parameters.Add(new SqlParameter("@PanaLaData", dateResult));
                //if (ModuleInfo.AnArhiva == String.Empty)
                //    ta.SelectCommand.Parameters.Add(new SqlParameter("@An", Convert.ToInt16(0)));
                //else
                //    ta.SelectCommand.Parameters.Add(new SqlParameter("@An", Convert.ToInt16(ModuleInfo.AnArhiva)));

                //ta.SelectCommand.Parameters.Add(new SqlParameter("@strFilter", FiltruRCDebit));
                //ta.SelectCommand.Parameters.Add(new SqlParameter("@strFilter2", FiltruRCCredit));
                //ta.SelectCommand.Parameters.Add(new SqlParameter("@strOrder", String.Empty));
                //if (!SortDataDocJust)
                //    ta.SelectCommand.Parameters.Add(new SqlParameter("@strFiltruNrNota", String.Empty));

                //ta.Fill(eSRPDS.NotaContabilaView);
                args.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("ESRPDataSet_NotaContabilaView", balcon_GenNotaContabilaUnionBindingSource));

            }

            InchideConexiune(sqlConn);
            if (ta != null)
                ta.Dispose();
        }

        private void addJurnal_Click(object sender, EventArgs e)
        {
            foreach (CapitoleSelectate cs in capitoleSelectateBindingSource)
            {
                if (cs.Name == jurnalCB.Text)
                    return;
            }

            capitoleSelectateBindingSource.Add(new CapitoleSelectate(jurnalCB.Text,
                Convert.ToInt16(jurnalCB.SelectedValue)));
            jurnaleRB.Checked = true;
        }

        private void delJurnal_Click(object sender, EventArgs e)
        {
            if (capitoleSelectateBindingSource.Current != null)
                capitoleSelectateBindingSource.RemoveCurrent();
        }


        private Boolean RegistruJurnal(PreviewRaportFrm frm, ESRPDataSetListe eSRPDS)
        {
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
           

            String filtruData = String.Empty;
            String filtruCat = String.Empty;
            String linia1 = String.Empty, linia2 = String.Empty;
            DateTime dt = DateTime.MaxValue, dte = DateTime.MinValue;
            
            dte = DeLaDataDTP.Value;
            filtruData = " DataDoc >= @DataStart ";
            
            dt = PanaLaDataDTP.Value;
            if (filtruData != String.Empty)
                filtruData += "AND ";
            filtruData += " DataDoc <= @DataEnd ";


            if (Convert.ToInt16(TipListaCB.SelectedValue) == 2)
                filtruCat = "[Categorie] = 2";
            else
                filtruCat = "[Categorie] = 0";

            String centralizat = "False";
            if (ZiPerPaginaCB.Checked)
                centralizat = "True";

            linia1 = "Registru Jurnal " + TipListaCB.Text;
            linia1 += " in intervalul " + dte.ToString("d", cultureRO) + " - " + dt.ToString("d", cultureRO);

            String dlc = String.Empty;
            if (ContDebitCB.Text != "---") dlc = ContDebitCB.Text;

            String plc = String.Empty;
            if (ContCreditCB.Text != "---") plc = ContCreditCB.Text;

            if (plc != String.Empty && dlc != String.Empty)
            {
                MessageBox.Show("Lista nu poate fi generata pentru un cont debit si un cont credit simultan!");
                return false;
            }

            String filtruContDebit = String.Empty;
            String filtruContCredit = String.Empty;
            String filtruCont = String.Empty;
            if (plc != String.Empty || dlc != String.Empty)
            {

                if (dlc != String.Empty)
                {
                    linia2 = "pentru contul " + dlc;
                    filtruContDebit += "ContDebit Like '" + dlc + "%'";
                    filtruCont = " AND " + filtruContDebit;
                }
                if (plc != String.Empty)
                {
                    linia2 += " pentru contul " + plc;
                    filtruContCredit += "ContCredit LIKE '" + plc + "%'";
                    filtruCont = " AND " + filtruContCredit;
                }

            }

            String sJurnal = GetJurnaleSelectate();

            String comanda = "AND ContDebit<>'N/A' AND ContCredit<>'N/A' ";
            String filtreTot = String.Empty;
            ///sectiunea de jurnale
            if (filtruCat != String.Empty)
            {
                filtreTot += " AND " + filtruCat;
            }


            SumDocFormula sdf = new SumDocFormula(cmd.Connection);
            if (dlc == String.Empty && plc == String.Empty)
                sdf.CalcSume(filtreTot, filtruContDebit, filtruContCredit, dte, dt, (sJurnal==String.Empty?"-1":sJurnal), false, ModuleInfo);
            else
                sdf.CalcSume(filtreTot, filtruContDebit, filtruContCredit, dte, dt, (sJurnal == String.Empty ? "-1" : sJurnal), true, ModuleInfo);

            if (sJurnal != String.Empty)
            {
                filtreTot += " AND [IdJurnal] in (" + sJurnal + ")";                
                linia2 += " pentru " + GetDenumireJurnaleSelectate();
            }

            if (filtruCont != String.Empty)
            {
                filtreTot += filtruCont;
            }
            comanda += filtreTot;

            notaContabilaViewTableAdapter.Connection = cmd.Connection;
            if(ModuleInfo.AnArhiva!=String.Empty)
                eSRPDataSetListe.EnforceConstraints = false;
           // this.notaContabilaViewTableAdapter.GenNotaContabila(this.eSRPDataSetListe.NotaContabilaView,String.Empty,ModuleInfo.CodUnitate,
            //    dte, dt,(ModuleInfo.AnArhiva == String.Empty?(short)0:Convert.ToInt16(ModuleInfo.AnArhiva)),comanda,String.Empty);

            this.notaContabilaViewTableAdapter.GenNotaContabila2(this.eSRPDataSetListe.NotaContabilaView,
                m_IdLista,
                String.Empty, 
                ModuleInfo.CodUnitate,
                dte, 
                dt, 
                (ModuleInfo.AnArhiva == String.Empty ? (short)0 : Convert.ToInt16(ModuleInfo.AnArhiva)),
                Convert.ToInt16(0), 
                String.Empty,
                String.Empty);

            frm.NumeRaport = "RegistruJurnal.rdlc";
            if (compactCB.Checked)
                frm.NumeRaport = "RegistruJurnalCompact.rdlc";
            else
                if (!bDocumentJustifRulaj)
                    frm.NumeRaport = "RegistruJurnalFaraJustificative.rdlc";

            //frm.dataloadHandler += new LoadDataHandler(frm_dataloadHandler);

            frm.AddDataSource("ESRPDataSet_BalconSetup", balconSetupBindingSource);
            frm.AddDataSource("ESRPDataSet_NotaContabilaView", notaContabilaViewBindingSource);
            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);

            frm.AddParameter("DebitInitial", sdf.debInit, true);
            frm.AddParameter("CreditInitial", sdf.creInit, true);
            frm.AddParameter("DebitPrecedent", sdf.debPrec, true);
            frm.AddParameter("CreditPrecedent", sdf.crePrec, true);
            frm.AddParameter("RulajDebit", sdf.rulajDeb, true);
            frm.AddParameter("RulajCredit", sdf.rulajCre, true);
            frm.AddParameter("TotalSumeDebit", sdf.totalDeb, true);
            frm.AddParameter("TotalSumeCredit", sdf.totalCre, true);
            frm.AddParameter("Centralizat", centralizat, true);

            //frm.AddParameter("Debit", Debit == "Debit" ? "True" : "False", true);
            frm.SetWindowFormat(false);
            InchideConexiune(cmd.Connection);
            return true;
        }

        private String GetJurnaleSelectate()
        {
            String ret = String.Empty;
            if (jurnalRB.Checked)
            {
                ret = jurnalCB.SelectedValue.ToString();
            }
            if (jurnaleRB.Checked)
            {
                for (Int16 i = 0; i < capitoleSelectateBindingSource.Count; i++)
                {
                    if (ret != String.Empty)
                        ret += ",";
                    ret += ((CapitoleSelectate)capitoleSelectateBindingSource.List[i]).Tag.ToString();
                }
            }
            return ret;
        }

        private String GetSurseFinantareSelectate()
        {
            String ret = String.Empty;
            if (SursaFinantareRB.Checked)
            {
                ret = SursaFinantareCB.SelectedValue.ToString();
            }
            if (SurseFinantareRB.Checked)
            {
                for (Int16 i = 0; i < surseFinantareSelectateBindingSource.Count; i++)
                {
                    if (ret != String.Empty)
                        ret += ",";
                    ret += ((CapitoleSelectate)surseFinantareSelectateBindingSource.List[i]).Tag.ToString();
                }
            }
            return ret;
        }

        private String GetDenumireJurnaleSelectate()
        {
            String ret = String.Empty;
            if (jurnalRB.Checked)
            {
                ret = jurnalCB.Text;
            }
            if (jurnaleRB.Checked)
            {
                for (Int16 i = 0; i < capitoleSelectateBindingSource.Count; i++)
                {
                    if (ret != String.Empty)
                        ret += ",";
                    ret += ((CapitoleSelectate)capitoleSelectateBindingSource.List[i]).Name;
                }
            }
            return ret;
        }

        String filtJurnal = String.Empty;
        StringBuilder filtNrNote = new StringBuilder();
        private void ExtrasDeCont(PreviewRaportFrm frm, ESRPDataSetListe eSRPDS, String Titlu)
        {

            if (bRowSetup.IsLiniiSemnaturaNull())
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare", "Vă rugăm să setați parametrul <<Linii după semnături>>!", String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, null);
                mbt.AddButton("Iesire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
                return;
            }

            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));

            String filtruData = String.Empty;
            DateTime dte = DateTime.MinValue, dt = DateTime.MaxValue;
            dte = DeLaDataDTP.Value;
            filtruData = " DataDoc >= @DataStart ";
            
            dt = PanaLaDataDTP.Value;
            if (filtruData != String.Empty)
                filtruData += "AND ";
            filtruData += " DataDoc <= @DataEnd ";

            String linia1 = Titlu + " ", linia2 = String.Empty; //+ tipJurn;
            linia1 += " in intervalul " + dte.ToString("d", cultureRO) + " - " + dt.ToString("d", cultureRO);

            String dlc = String.Empty;
            String plc = String.Empty;
            if (ContDebitCB.Text != "---") dlc = ContDebitCB.Text;
            if (ContDebitCB.Text != "---") plc = ContCreditCB.Text;
            
            String filtreTot = String.Empty, filtreTotSuma = String.Empty, filtreTotCredit = String.Empty;
            String filtruCont = String.Empty;
            String filtruContCredit = String.Empty;
            if (plc != String.Empty || dlc != String.Empty)
            {
                if (dlc != String.Empty)
                {
                    linia2 = "de la contul " + dlc;
                    filtruCont = " AND ContDebit >= '" + dlc + "'";
                    filtruContCredit = " AND ContCredit >= '" + dlc + "'";
                    filtreTotSuma = " AND Cont >= '" + dlc + "'";
                }
                if (plc != String.Empty)
                {
                    linia2 += " pana la contul " + plc;
                    filtruCont += " AND ContDebit <= '" + plc + "'";
                    filtruContCredit += " AND ContCredit <= '" + plc + "'";
                    filtreTotSuma += " AND Cont <= '" + plc + "'";
                    if (plc == dlc)
                    {
                        linia2 = " pentru contul " + plc;
                        filtruCont = " AND ContDebit LIKE '" + plc + "%'";
                        filtruContCredit = " AND ContCredit LIKE '" + plc + "%'";
                        filtreTotSuma = " AND Cont LIKE '" + plc + "%'";
                    }
                }

            }

           
            for (int i = 0; i < IgnoraNoteCB.Items.Count; i++)
            {
                if (IgnoraNoteCB.GetItemChecked(i))
                {
                    if (filtNrNote.Length > 0)
                        filtNrNote.Append(",");
                    filtNrNote.Append("'" + IgnoraNoteCB.Items[i].ToString().Trim() + "'");
                }
            }
            if (IgnoraNoteCB.CheckedItems.Count == IgnoraNoteCB.Items.Count)
                filtNrNote.Remove(0, filtNrNote.Length);

     

            String sJurnal = GetJurnaleSelectate();
            this.balcon_GenExtrasContTableAdapter.Connection = cmd.Connection;
            this.eSRPDataSetListe.EnforceConstraints = false;
            this.balcon_GenExtrasContTableAdapter.Fill(this.eSRPDataSetListe.balcon_GenExtrasCont,
                ModuleInfo.CodUnitate, DeLaDataDTP.Value, PanaLaDataDTP.Value, String.Empty, dlc, plc, filtNrNote.ToString(),sJurnal);

            //String comanda = "SELECT ContDebit,ContCredit,'D' AS Tip,NumarDoc,DataDoc,NumarNota,ValoareLei,IdJurnal,TipDocJust,NumarDocJust,DataDocJust,ExplicatiiDocJust,TipFormula,Categorie FROM NotaContabilaView WHERE [ContDebit]<>'N/A' " + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            //String Comanda2 = "SELECT ContCredit AS ContDebit,ContDebit AS ContCredit,'C' AS Tip,NumarDoc,DataDoc,NumarNota,ValoareLei,IdJurnal,TipDocJust,NumarDocJust,DataDocJust,ExplicatiiDocJust,TipFormula,Categorie FROM NotaContabilaView WHERE [ContCredit]<>'N/A' " + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();

            ///sectiunea de jurnale
            if (filtruCont != String.Empty)
            {
                filtreTot += filtruCont;
                filtreTotCredit += filtruContCredit;
            }

            SumDocFormula sdf = new SumDocFormula(cmd.Connection);
            sdf.CalcTotal(filtreTotSuma, dte, dt, sJurnal, ModuleInfo, filtNrNote.ToString());

            
            if (sJurnal != String.Empty)
            {
                filtreTot += " AND [IdJurnal] in (" + sJurnal + ")";                
                filtreTotCredit += " AND [IdJurnal] in (" + sJurnal + ")";
                linia2 += " pentru " + GetDenumireJurnaleSelectate();
                filtJurnal = sJurnal; 
            }

            //FiltruRCCredit = filtreTotCredit;
            //FiltruRCDebit = filtreTot;

            
            FiltruJurnal = filtJurnal;



            frm.NumeRaport = "ExtrasDeCont.rdlc";
            if(!bDocumentJustifRulaj)
                frm.NumeRaport = "ExtrasDeContFaraDocJust.rdlc";

            frm.dataloadHandler += new LoadDataHandler(frm_dataloadHandlerExtrasCont);

            frm.AddDataSource("ESRPDataSet_BalconSetup", balconSetupBindingSource);
            frm.AddDataSource("balcon_GenRegistruCasa", balcon_GenExtrasContBindingSource);


            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);

            frm.AddParameter("DebitInitial", sdf.debInit, true);
            frm.AddParameter("CreditInitial", sdf.creInit, true);
            frm.AddParameter("DebitPrecedent", sdf.debPrec, true);
            frm.AddParameter("CreditPrecedent", sdf.crePrec, true);
            frm.AddParameter("RulajDebit", sdf.debCurent, true);
            frm.AddParameter("RulajCredit", sdf.creCurent, true);
            frm.AddParameter("TotalSumeDebit", sdf.totalDeb, true);
            frm.AddParameter("TotalSumeCredit", sdf.totalCre, true);

            frm.AddParameter("ContCoresp", ContCorespondentCB.Checked ? "True" : "False", true);
            frm.AddParameter("DocumentJustificativ", (bDocumentJustifRulaj ? "True" : "False"), true);

            Boolean bPaginaPerZi = false;
            String l1s = String.Empty, l2s = String.Empty, l3s = String.Empty, l1d = String.Empty, l2d = String.Empty, l3d = String.Empty;

            frm.AddParameter("PaginaPerZi", (bPaginaPerZi ? "True" : "False"), true);
            frm.AddParameter("Antet1Stanga", bRowSetup.IsLinia1StangaNull()?"":bRowSetup.Linia1Stanga, true);
            frm.AddParameter("Antet2Stanga", bRowSetup.IsLinia2StangaNull()?"":bRowSetup.Linia2Stanga, true);
            frm.AddParameter("Antet3Stanga", bRowSetup.IsLinia3StangaNull()?"":bRowSetup.Linia3Stanga, true);
            frm.AddParameter("Antet1Dreapta", bRowSetup.IsLinia1DreaptaNull()?"":bRowSetup.Linia1Dreapta, true);
            frm.AddParameter("Antet2Dreapta", bRowSetup.IsLinia2DreaptaNull()?"":bRowSetup.Linia2Dreapta, true);
            frm.AddParameter("Antet3Dreapta", bRowSetup.IsLinia3DreaptaNull()?"":bRowSetup.Linia3Dreapta, true);
            frm.AddParameter("DataInTitlu", "False", true);
            frm.AddParameter("GroupDataDocJust", "False", true);
            frm.SetWindowFormat(true);
            InchideConexiune(cmd.Connection);
        }


        public void frm_dataloadHandlerExtrasCont(object sender, Microsoft.Reporting.WinForms.SubreportProcessingEventArgs args)
        {
            SqlConnection sqlConn = DeschideConexiune(workConnString);

            if (args.ReportPath == "ExtrasDeContSubreport")
            {
                Trace.Assert(args.Parameters.Count == 7, "Numar incorect de parametrii la subraport");
                CultureInfo culture;
                DateTimeStyles styles;
                DateTime dateResult;

                culture = Application.CurrentCulture;
                styles = DateTimeStyles.None;

                if (!DateTime.TryParse(args.Parameters["Data"].Values[0], culture, styles, out dateResult))
                    return;

                balcon_GenNCExtrasContTableAdapter.Connection = sqlConn;
                this.balcon_GenNCExtrasContTableAdapter.Fill(this.eSRPDataSetListe.balcon_GenNCExtrasCont,
                    args.Parameters["Cont"].Values[0],
                    ModuleInfo.CodUnitate,
                    dateResult,
                    dateResult, 
                    0, 
                    filtJurnal, 
                    filtNrNote.ToString());

                args.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("ESRPDataSet_NotaContabilaView", balcon_GenNCExtrasContBindingSource));

            }
            InchideConexiune(sqlConn);
        }

        private Int16 tipListaBalanta = 0;
        private void Balanta(PreviewRaportFrm frm, ESRPDataSetListe eSRPDS)
        {
            MyTrace("0-->>Balanta");
            tipListaBalanta = 0;
            SqlConnection con = DeschideConexiune(workConnString, 600);

            DateTime dt = DateTime.Now;
            String linia1 = String.Empty, linia2 = String.Empty, filtruTotal = String.Empty;

            dt = DeLaDataDTP.Value;

            MyTrace("0----Read LDT value");
            if (AnaliticaCB.Checked)
            {
                linia1 = "Balanta analitica ";
                //filtruTotal = " AND [EsteAnalitic]= 1";
				tipListaBalanta = 1;
            }
            else
            {
                linia1 = "Balanta sintetica ";
                //filtruTotal = " AND [EsteAnalitic]= 0";
            }
            MyTrace("0----Read ANL value");
            linia1 += " la data " + dt.ToString("d", cultureRO);
            MyTrace("0----Read TPB value");
            Int32 categorieSelectata = 0;
            if (Convert.ToInt16(TipListaCB.SelectedValue) == 0)
            {
                filtruTotal += " AND [Categorie]= 0";
            }
            else
            {
                categorieSelectata = 2;
                filtruTotal += " AND [Categorie]= 2";
            }

			String dlc = ContDebitCB.Text == "---" ? String.Empty : ContDebitCB.Text;
			String plc = ContCreditCB.Text == "---" ? String.Empty : ContCreditCB.Text;


            if (plc != String.Empty || dlc != String.Empty)
            {
                if (dlc != String.Empty)
                {
                    linia2 = "de la contul " + dlc;
                    filtruTotal += " AND Cont>='" + dlc + "'";
                }
                if (plc != String.Empty)
                {
                    linia2 += " pana la contul " + plc;
                    filtruTotal += " AND Cont<='" + plc + "'";
                }
            }


            String sJurnal = GetJurnaleSelectate();
            if (sJurnal != String.Empty)
            {
                linia2 += " pentru " + GetDenumireJurnaleSelectate();
            }
            String sSursaFinantare = GetSurseFinantareSelectate();
            if (sSursaFinantare != String.Empty)
            {
                linia2 += " pentru Sursele de finantare:" + sSursaFinantare;
            }

            try {
                
                    this.balcon_GenListaBalanta2014TableAdapter.Connection = con;
                
                    //this.balcon_GenListaBalanta2014TableAdapter.Adapter.SelectCommand.CommandTimeout = 600;
                    this.balcon_GenListaBalanta2014TableAdapter.Fill(this.eSRPDataSetListe.balcon_GenListaBalanta2014,
                        (short?)(ModuleInfo.AnArhiva == String.Empty ? 0 : Convert.ToInt16(ModuleInfo.AnArhiva)),
                        ModuleInfo.CodUnitate,
                        (byte?)categorieSelectata,
                        AnaliticaCB.Checked,
                        ConturiFaraMiscariCB.Checked,
                        sJurnal,
                        DeLaDataDTP.Value,
                        DeLaDataDTP.Value,
                        TotalGrupeSiClaseCB.Checked,
                        dlc,
                        plc,
                        ContExtinsCB.Checked,
                        sSursaFinantare,
                        FiltruAnaliticTB.Text.Trim(), false);

               
                }
            catch(Exception ex)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare", ex.Message, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, null);
                mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
                return;
            }
            MyTrace("0----Fill BalantaView");
            //listBS[1].Sort = "SortValue";

            frm.NumeRaport = "Balanta.rdlc";
            if (compactCB.Checked)
                frm.NumeRaport = "BalantaCompact.rdlc";
            if (Convert.ToInt16(TipBalantaCB.SelectedValue)==1)
            {
                frm.NumeRaport = "BalantaICLTS.rdlc";
                if (compactCB.Checked)
                    frm.NumeRaport = "BalantaICLTSCompact.rdlc";
            }
            else
                if (Convert.ToInt16(TipBalantaCB.SelectedValue) == 2)
                {
                    frm.NumeRaport = "BalantaICTLS.rdlc";
                    if (compactCB.Checked)
                        frm.NumeRaport = "BalantaICTLSCompact.rdlc";
                }
            if (TotalGrupeSiClaseCB.Checked)
                frm.NumeRaport = "BalantaTCG.rdlc";

            frm.AddDataSource("ESRPDataSet_BalantaView", balcon_GenListaBalanta2014BindingSource);
            frm.AddDataSource("ESRPDataSet_BalconSetup", balconSetupBindingSource);
            //frm.AddDataSource("ESRPDataSet_Semnaturi", listBS[2]);
            MyTrace("0----add data source");

            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);

            if (frm.NumeRaport == "BalantaICLTS.rdlc" || frm.NumeRaport == "BalantaICTLS.rdlc")
            {
                SqlCommand cmd = new SqlCommand(String.Empty,con);
                cmd.CommandText = "SELECT COUNT(*) FROM [SemnaturiListe] WHERE  IDLista=" + m_IdLista + " AND [TipLista]=" + tipListaBalanta;
                Boolean eSemnaturi = Convert.ToInt32(cmd.ExecuteScalar()) != 0;
                frm.AddParameter("Semnaturi", eSemnaturi ? "True" : "False", true);
            }
            frm.AddParameter("Analitica", AnaliticaCB.Checked?"True":"False", true);

            frm.SetWindowFormat(true);
            frm.dataloadHandler += new LoadDataHandler(balanta_dataloadHandler);
            InchideConexiune(con);
            MyTrace("<<--oBalanta");

            
			
        }

        public void balanta_dataloadHandler(object sender, Microsoft.Reporting.WinForms.SubreportProcessingEventArgs args)
        {
            if (args.ReportPath == "SemnaturiSubReport")
            {
                ESRPDataSet eSRPDS = new ESRPDataSet();
                BindingSource bs = null;
                SqlDataAdapter ta = null;
                SqlConnection sqlConn = DeschideConexiune(workConnString);

           
                    bs = new BindingSource(eSRPDS, "Semnaturi");
                    ta = new SqlDataAdapter("SELECT TOP 3 * FROM [Semnaturi] s JOIN [SemnaturiListe]  sl ON s.IDSemnatura=sl.IDSemnatura  WHERE sl.IDLista=" + m_IdLista.ToString() + " AND sl.[TipLista]=" + tipListaBalanta.ToString(), sqlConn);
                    ta.Fill(eSRPDS.Semnaturi);
                    args.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("ESRPDataSet_Semnaturi", bs));
            

                InchideConexiune(sqlConn);
                if (ta != null)
                    ta.Dispose();
            }
        }

        private void LoadFormInfo()
        {
            String FileName = "OptiuniRapoarteFrm.xml";
            if (File.Exists(FileName))
            {
                Stream stream = File.Open(FileName, FileMode.Open);
                BinaryFormatter formatter = new BinaryFormatter();

                //formatter = new BinaryFormatter();
                formatter.Binder = new PreMergeToMergedDeserializationBinder();

                try
                {
                    
                    _fInfoSave = (FormSaveInfo)formatter.Deserialize(stream);
                }
                catch(Exception ex)
                {
                    MyTrace(ex.Message);
                    _fInfoSave = new FormSaveInfo();
                }
                stream.Close();
                formSaveInfoBindingSource.Add(_fInfoSave);
            }

        }

        private void OptiuniRapoarteFrm_FormClosed(object sender, FormClosedEventArgs e)
        {
            String FileName = "OptiuniRapoarteFrm.xml";
            Stream stream = File.Open(FileName, FileMode.Create);
            BinaryFormatter formatter = new BinaryFormatter();
           
            formatter.Serialize(stream, _fInfoSave);
            stream.Close();
        }

        private void addSS_Click(object sender, EventArgs e)
        {
            foreach (CapitoleSelectate cs in surseFinantareSelectateBindingSource)
            {
                if (cs.Name == SursaFinantareCB.Text)
                    return;
            }
            surseFinantareSelectateBindingSource.Add(new CapitoleSelectate(SursaFinantareCB.Text,SursaFinantareCB.SelectedValue.ToString()));
            SurseFinantareRB.Checked = true;

        }

        private void delSS_Click(object sender, EventArgs e)
        {
            if (surseFinantareSelectateBindingSource.Current!=null)
                surseFinantareSelectateBindingSource.RemoveCurrent();
        }

        private void ExecutieCheltuieli(PreviewRaportFrm frm, ESRPDataSetListe eSRPDS)
        {

            SqlConnection con= DeschideConexiune(workConnString,600);

            String linia1 = String.Empty, linia2 = String.Empty;

            String capitol = String.Empty;

            linia1 = "CONTUL DE EXECUTIE AL INSTITUTIILOR PUBLICE - Cheltuieli ";
            linia2 = " la data " + PanaLaDataDTP.Value.ToString("d", cultureRO);
            if (m_IdLista == 11)
            {
                linia1 = "Executia cheltuielilor bugetare ";
                linia2 = " de la data " + DeLaDataDTP.Value.ToString("d", cultureRO) + " pana la " + PanaLaDataDTP.Value.ToString("d", cultureRO);
            }


            String dlc = String.Empty;
            String plc = String.Empty;
            if (ContDebitCB.Text != "---") dlc = ContDebitCB.Text;
            if (ContDebitCB.Text != "---") plc = ContCreditCB.Text;

            if (plc != String.Empty || dlc != String.Empty)
            {
                if (dlc != String.Empty)
                {
                    linia2 += " de la contul " + dlc;
                }
                if (plc != String.Empty)
                {
                    linia2 += " pana la contul " + plc;
                }
            }

            String sJurnal = GetJurnaleSelectate();
            if (sJurnal != String.Empty)
            {
                linia2 += " pentru " + GetDenumireJurnaleSelectate();
            }


            String sSursaFinantare = GetSurseFinantareSelectate();
            if (sSursaFinantare != String.Empty)
            {
                linia2 += " pentru Sursele de finantare:" + sSursaFinantare;
            }

            for (int i = 0; i < IgnoraNoteCB.Items.Count; i++)
            {
                if (IgnoraNoteCB.GetItemChecked(i))
                {
                    if (filtNrNote.Length > 0)
                        filtNrNote.Append(",");
                    filtNrNote.Append("'" + IgnoraNoteCB.Items[i].ToString().Trim() + "'");
                }
            }
            if (IgnoraNoteCB.CheckedItems.Count == IgnoraNoteCB.Items.Count)
                filtNrNote.Remove(0, filtNrNote.Length);


            this.balcon_GenListaExecutieCheltTableAdapter.Connection = con;
            if (ModuleInfo.AnArhiva==String.Empty)
            this.balcon_GenListaExecutieCheltTableAdapter.Fill(this.eSRPDataSetListe.balcon_GenListaExecutieChelt,
                (short)tipRaport, 
                DeLaDataDTP.Value,
                PanaLaDataDTP.Value,
                dlc, 
                plc, 
                ModuleInfo.CodUnitate, 
                filtNrNote.ToString(),
                CentralizatCB.Checked, 
                ConturiFaraMiscariCB.Checked, 
                sSursaFinantare, 
                sJurnal,
                ModuleInfo.AnArhiva);
            else
                this.balcon_GenListaExecutieCheltTableAdapter.FillByArh(this.eSRPDataSetListe.balcon_GenListaExecutieChelt,
                (short)tipRaport,
                DeLaDataDTP.Value,
                PanaLaDataDTP.Value,
                dlc,
                plc,
                ModuleInfo.CodUnitate,
                filtNrNote.ToString(),
                CentralizatCB.Checked,
                ConturiFaraMiscariCB.Checked,
                sSursaFinantare,
                sJurnal,
                ModuleInfo.AnArhiva);

            frm.NumeRaport = "ContExecutieInstitutii.rdlc";
            if (tipRaport == TipLista.ExecutieCheltuieli)
                frm.NumeRaport = "ExecutieCheltCentralizata.rdlc";


            frm.AddDataSource("ESRPDataSet_BalconSetup", balconSetupBindingSource);
            frm.AddDataSource("ESRPDataSet_ExcutieCheltuieliCentralizata", balcon_GenListaExecutieCheltBindingSource);


            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);
            frm.AddParameter("Capitol", capitol, true);

            SqlCommand cmd = new SqlCommand(String.Empty,con);
            cmd.CommandText = "SELECT COUNT(*) FROM [SemnaturiListe] WHERE  IDLista=" + m_IdLista + " AND [TipLista]=0";
            Boolean eSemnaturi = Convert.ToInt32(cmd.ExecuteScalar()) != 0;
            frm.AddParameter("Semnaturi", eSemnaturi ? "True" : "False", true);

            frm.SetWindowFormat(true);
            frm.dataloadHandler += new LoadDataHandler(balanta_dataloadHandler);
            InchideConexiune(con);
        }

        private void FisaCont(PreviewRaportFrm frm, ESRPDataSetListe eSRPDS)
        {
            
            tipListaBalanta = 0;
            SqlConnection con = DeschideConexiune(workConnString, 600);

            DateTime dt = DateTime.Now;
            String linia1 = String.Empty, linia2 = String.Empty, filtruTotal = String.Empty;

            dt = DeLaDataDTP.Value;

            if (AnaliticaCB.Checked)
            {
                linia1 = "Fisa cont analitica ";
				tipListaBalanta = 1;
            }
            else
            {
                linia1 = "Fisa cont sintetica ";
            }

            linia1 += " in intervalul " + DeLaDataDTP.Value.ToString("d", cultureRO) + " - " + PanaLaDataDTP.Value.ToString("d", cultureRO);

            Int32 categorieSelectata = 0;
            if (Convert.ToInt16(TipListaCB.SelectedValue) == 0)
            {
                filtruTotal += " AND [Categorie]= 0";
            }
            else
            {
                categorieSelectata = 2;
                filtruTotal += " AND [Categorie]= 2";
            }

			String dlc = ContDebitCB.Text == "---" ? String.Empty : ContDebitCB.Text;
			String plc = ContCreditCB.Text == "---" ? String.Empty : ContCreditCB.Text;


            if (plc != String.Empty || dlc != String.Empty)
            {
                if (dlc != String.Empty)
                {
                    linia2 = "de la contul " + dlc;
                    filtruTotal += " AND Cont>='" + dlc + "'";
                }
                if (plc != String.Empty)
                {
                    linia2 += " pana la contul " + plc;
                    filtruTotal += " AND Cont<='" + plc + "'";
                }
            }


            String sJurnal = GetJurnaleSelectate();
            if (sJurnal != String.Empty)
            {
                linia2 += " pentru " + GetDenumireJurnaleSelectate();
            }
            String sSursaFinantare = GetSurseFinantareSelectate();
            if (sSursaFinantare != String.Empty)
            {
                linia2 += " pentru Sursele de finantare:" + sSursaFinantare;
            }

            try {
                
                    this.balcon_GenListaBalanta2014TableAdapter.Connection = con;
                
                    //this.balcon_GenListaBalanta2014TableAdapter.Adapter.SelectCommand.CommandTimeout = 600;
                    this.balcon_GenListaBalanta2014TableAdapter.Fill(this.eSRPDataSetListe.balcon_GenListaBalanta2014,
                        (short?)(ModuleInfo.AnArhiva == String.Empty ? 0 : Convert.ToInt16(ModuleInfo.AnArhiva)),
                        ModuleInfo.CodUnitate,
                        (byte?)categorieSelectata,
                        AnaliticaCB.Checked,
                        ConturiFaraMiscariCB.Checked,
                        sJurnal,
                        DeLaDataDTP.Value,
                        PanaLaDataDTP.Value,
                        TotalGrupeSiClaseCB.Checked,
                        dlc,
                        plc,
                        ContExtinsCB.Checked,
                        sSursaFinantare,
                        FiltruAnaliticTB.Text.Trim(), true);

               
                }
            catch(Exception ex)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare", ex.Message, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, null);
                mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
                return;
            }


            frm.NumeRaport = "FisaCont.rdlc";
            if (compactCB.Checked || bRowSetup.TipUnitate.Trim()=="B")
                frm.NumeRaport = "FisaContCompact.rdlc";

            frm.dataloadHandler += new LoadDataHandler(FisaCont_dataloadHandler);
            balcon_GenListaBalanta2014BindingSource.Sort = "SortValue";
            frm.AddDataSource("ESRPDataSet_BalantaView", balcon_GenListaBalanta2014BindingSource);
            frm.AddDataSource("ESRPDataSet_BalconSetup", balconSetupBindingSource);

            frm.AddParameter("DeLaData", DeLaDataDTP.Value.ToOADate().ToString(), true);
            frm.AddParameter("PanaLaData", PanaLaDataDTP.Value.ToOADate().ToString(), true);
            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);
            frm.AddParameter("Analitica", AnaliticaCB.Checked ? "True" : "False", true);
            frm.AddParameter("DocJust", bDocumentJustifRulaj ? "True" : "False", true);
            SqlCommand cmd = new SqlCommand(String.Empty, con);
            cmd.CommandText = "SELECT COUNT(*) FROM [SemnaturiListe] WHERE  IDLista=" + m_IdLista + " AND [TipLista]=" + tipListaBalanta.ToString();
            Boolean eSemnaturi = Convert.ToInt32(cmd.ExecuteScalar()) != 0;
            frm.AddParameter("Semnaturi", eSemnaturi ? "True" : "False", true);

            frm.SetWindowFormat(true);
            InchideConexiune(con);
        }

        public void FisaCont_dataloadHandler(object sender, Microsoft.Reporting.WinForms.SubreportProcessingEventArgs args)
        {
            ESRPDataSetListe eSRPDS = new ESRPDataSetListe();
            BindingSource bs = null;
            
            SqlConnection sqlConn = DeschideConexiune(workConnString);

            if (args.ReportPath == "SemnaturiSubReport")
            {
                SqlDataAdapter ta = null;
                bs = new BindingSource(eSRPDS, "Semnaturi");
                ta = new SqlDataAdapter("SELECT TOP 3 * FROM [Semnaturi] s JOIN [SemnaturiListe]  sl ON s.IDSemnatura=sl.IDSemnatura  WHERE sl.IDLista=" + m_IdLista.ToString() + " AND sl.[TipLista]=" + tipListaBalanta.ToString(), sqlConn);
                ta.Fill(eSRPDS.Semnaturi);
                args.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("ESRPDataSet_Semnaturi", bs));

                InchideConexiune(sqlConn);
                if (ta != null)
                    ta.Dispose();
                return;

            }

            String cont = args.Parameters["cont"].Values[0];
            Decimal soldInitial = Convert.ToDecimal(args.Parameters["SoldPrecedent"].Values[0]);
            DateTime dld = DateTime.FromOADate(Convert.ToDouble(args.Parameters["DeLaData"].Values[0]));
            DateTime pld = DateTime.FromOADate(Convert.ToDouble(args.Parameters["PanaLaData"].Values[0]));
            bs = new BindingSource(eSRPDS, "balcon_GenNotaContabilaFC");
            this.balcon_GenNotaContabilaFCTableAdapter.Connection = sqlConn;
            this.balcon_GenNotaContabilaFCTableAdapter.Fill(eSRPDS.balcon_GenNotaContabilaFC,
                m_IdLista,
                cont,
                Convert.ToInt16(ModuleInfo.CodUnitate),
                dld,
                pld,
                (ModuleInfo.AnArhiva == String.Empty ? (Int16)0 : Convert.ToInt16(ModuleInfo.AnArhiva)),
                0,
                String.Empty,
                String.Empty);


            //for (int i = 0; i < bs.Count; i++)
            bs.Sort = "DataDoc";
            foreach (DataRowView drv in bs)
            {
                //ESRPDataSetListe.balcon_GenNotaContabilaFCRow dr = ((DataRowView)bs.List[i]).Row as ESRPDataSetListe.balcon_GenNotaContabilaFCRow;
                ESRPDataSetListe.balcon_GenNotaContabilaFCRow dr = drv.Row as ESRPDataSetListe.balcon_GenNotaContabilaFCRow;
                if (dr.ContDebit.Contains(cont))
                    soldInitial += dr.ValoareLei;
                else
                    if (dr.ContCredit.Contains(cont))
                        soldInitial -= dr.ValoareLei;

                dr.TipSold = (soldInitial >= 0) ? "D" : "C";
                dr.Sold = Math.Abs(soldInitial);
            }

            args.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("ESRPDataSet_NotaContabilaView", bs));

            InchideConexiune(sqlConn);
        }

        private void ContDebitB_Click(object sender, EventArgs e)
        {
            FrmRezumat rez = null;
            if (ModuleInfo.AnArhiva != String.Empty)
            {
                rez = new ArhConturiRezumatFrm(ModuleInfo);
            }
            else
                rez = new ConturiRezumatFrm(ModuleInfo);

            rez.SelectionAddOn = true;
            if (rez.ShowDialog() == DialogResult.OK)
            {
                ContDebitCB.SelectedValue =
                    rez.selectedRow.Cells["ContColumn"].Value;
               
            }
        }

        private void ContCreditB_Click(object sender, EventArgs e)
        {
            FrmRezumat rez = null;
            if (ModuleInfo.AnArhiva != String.Empty)
            {
                rez = new ArhConturiRezumatFrm(ModuleInfo);
            }
            else
                rez = new ConturiRezumatFrm(ModuleInfo);

            rez.SelectionAddOn = true;
            if (rez.ShowDialog() == DialogResult.OK)
            {
                ContCreditCB.SelectedValue =
                    rez.selectedRow.Cells["ContColumn"].Value;

            }
        }

        


    }

    sealed class PreMergeToMergedDeserializationBinder : SerializationBinder
    {
        public override Type BindToType(string assemblyName, string typeName)
        {
            Type typeToDeserialize = null;

            // For each assemblyName/typeName that you want to deserialize to
            // a different type, set typeToDeserialize to the desired type.
            String exeAssembly = Assembly.GetExecutingAssembly().FullName;


            // The following line of code returns the type.
            typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
                typeName, exeAssembly));

            return typeToDeserialize;
        }
    }

    [Serializable()]
    public class FormSaveInfo
    {
        public FormSaveInfo(){ }

        public short TipBalanta {get;set;}
        
    }


    [Serializable()]
    public class CapitoleSelectate
    {
        public CapitoleSelectate(String nume, Decimal tag)
        {
            _Name = nume;
            _Tag2 = tag;
        }

        public CapitoleSelectate(String nume, Int64 tag)
        {
            _Name = nume;
            _Tag = tag;
        }

        public CapitoleSelectate(String nume, String tag)
        {
            _Name = nume;
            _Tag3 = tag;
        }

        private String _Name = String.Empty;
        [System.ComponentModel.Bindable(true)]
        public String Name
        {
            get
            {
                return _Name;
            }
            set
            {
                _Name = value;
            }
        }
        private Int64 _Tag = 0;
        [System.ComponentModel.Bindable(true)]
        public Int64 Tag
        {
            get
            {
                return _Tag;
            }
            set
            {
                _Tag = value;
            }
        }

        private Decimal _Tag2 = 0;
        [System.ComponentModel.Bindable(true)]
        public Decimal Tag2
        {
            get
            {
                return _Tag2;
            }
            set
            {
                _Tag2 = value;
            }
        }

        private String _Tag3 = String.Empty;
        [System.ComponentModel.Bindable(true)]
        public String Tag3
        {
            get
            {
                return _Tag3;
            }
            set
            {
                _Tag3 = value;
            }
        }
    }

    public class balcon_GenListaBalanta2014TableAdapterEx : ESRPDataSetListeTableAdapters.balcon_GenListaBalanta2014TableAdapter
    {
        public override int Fill(ESRPDataSetListe.balcon_GenListaBalanta2014DataTable dataTable, global::System.Nullable<short> An, 
            global::System.Nullable<short> CodUnitate, global::System.Nullable<byte> categorie, global::System.Nullable<bool> analitica, 
            global::System.Nullable<bool> cfm, string filtruJurnale,
            global::System.Nullable<global::System.DateTime> DataStart,
            global::System.Nullable<global::System.DateTime> DataEnd, global::System.Nullable<bool> ptgc, string ContStart, string ContEnd, global::System.Nullable<bool> Extinsa, string filtruSurseFinantare,String FiltruAnalitic,
            global::System.Nullable<bool> useDataStart
            )
        {
            this.CommandCollection[0].CommandTimeout=600;
            return base.Fill(dataTable, An, CodUnitate, categorie, analitica,
                cfm, filtruJurnale, DataStart, DataEnd, ptgc, ContStart, ContEnd, Extinsa, filtruSurseFinantare, FiltruAnalitic, useDataStart);
        }

    }
}
